/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package za.ac.cput.DesignPatterns.behavioral.interpreter;

import java.util.Map;
import java.util.Stack;

/**
 *
 * @author 210017252
 */
public class Evaluator implements  Expression{

    private Expression syntaxTree;
     String expression;

    public void setExpression(String exp) {
        exp = expression;
    }
    
    public String getExpression() {
        return expression;
    }

  
    
    
    
    
    public Evaluator(String exp) {
       expression=exp;
        Stack<Expression> expressionStack = new Stack<Expression>();
        
        for (String token : expression.split(" ")) {
            if  (token.equals("+")) {
                Expression subExpression = new Plus(expressionStack.pop(), expressionStack.pop());
                expressionStack.push( subExpression );
            }
            else if (token.equals("-")) {
               
                Expression right = expressionStack.pop();

                Expression left = expressionStack.pop();
                Expression subExpression = new Minus(left, right);
                expressionStack.push( subExpression );
            }
            else                        
                expressionStack.push( new Variable(token) );
        }
        syntaxTree = expressionStack.pop();
    }

    
    public Expression getSyntaxTree() {
        return syntaxTree;
    }

    public void setSyntaxTree(Expression syntaxTree) {
        this.syntaxTree = syntaxTree;
    }
    
    
    
    
    @Override
    public int interpret(Map<String, Expression> context) {
             return syntaxTree.interpret(context);
    }
    
    
    
    
}
